package com.dubbo.common.encode_zxing;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 使用  zxing 生成二维码
 * @author lianglie
 * @date 2018年11月24日 下午5:59:15
 */
public class ZxingEncodeUtils {

	/**
	 * 生成二维码
	 * @author lianglie
	 * @date 2018年11月24日 下午6:00:20
	 * @param content 二维码中的信息
	 * @param width 宽度
	 * @param height 高度
	 * @return byte[]
	 * @throws IOException
	 */
	@SuppressWarnings("all")
	public static byte[] createEncode(String content,Integer width,Integer height) throws IOException {
		ByteArrayOutputStream out = null;
		out = new ByteArrayOutputStream();
		String format="png";
		Hashtable hints=new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		hints.put(EncodeHintType.MARGIN, 2);
		try {
			BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
			MatrixToImageWriter.writeToStream(bitMatrix, format, out);
		} catch (WriterException e) {
			System.out.println("生成二维码失败");
		e.printStackTrace();
		}
		out.close();
		return out.toByteArray();
	}
//		解析二维码：
//
//		public static void main(String[] args) throws NotFoundException {
//		MultiFormatReader formatReader=new MultiFormatReader();
//		File file =new File("D:/new.png");
//		BufferedImage image=null;
//		try {
//		image = ImageIO.read(file);
//		} catch (IOException e) {
//		e.printStackTrace();
//		}
//		BinaryBitmap binaryBitmap =new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//		Hashtable hints=new Hashtable();
//		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//		Result result=formatReader.decode(binaryBitmap,hints);
//		System.err.println("解析结果："+result.toString());
//		System.out.println(result.getBarcodeFormat());
//		System.out.println(result.getText());
//
//
//	} 

}
